/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.controller;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.domain.Result;
import com.lam.common.base.page.TableHelper;
import com.lam.common.constant.CommonConstant;
import com.lam.common.context.TokenUtils;
import com.lam.framework.operLog.annotation.Log;
import com.lam.mall.api.service.UserAddrApiService;
import com.lam.mall.app.param.AddrParam;
import com.lam.mall.app.vo.UserAddrVo;
import com.lam.mall.entity.UserAddr;
import com.lam.mall.param.UserAddrParam;
import com.lam.mall.service.UserAddrService;

import cn.hutool.core.bean.BeanUtil;

/**
 * @author lam
 */
@RestController
@RequestMapping("/${frontPath}/address")
@Log(title = "地址接口")
public class AddrApiController {

    @Autowired
    private UserAddrService userAddrService;
    @Autowired
    private UserAddrApiService userAddrApiService;

    /**
     * 选择订单配送地址
     */
    @Log(oper = "用户地址列表")
    @GetMapping("/list")
    public Result dvyList() {
    	
        UserAddrParam param = new UserAddrParam();
        param.setUserId(TokenUtils.getLoginUserid());
        TableHelper.orderByColumn("default_addr", "desc");
        List<UserAddr> userAddrs = userAddrService.selectList(param);
        return Result.ok(BeanUtil.copyToList(userAddrs, UserAddrVo.class));
    }

    @PostMapping("/addAddr")
    @Log(oper = "新增用户地址")
    public Result addAddr(@Valid @RequestBody AddrParam addrParam) {

        if (addrParam.getId() != null) {
            return Result.fail("该地址已存在");
        }
        
        String userId = TokenUtils.getLoginUserid();
        long addrCount = userAddrApiService.countByUserId(userId);
        
        UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class);
        if (addrCount == 0) {
            userAddr.setDefaultAddr(CommonConstant.YES1);
        } else {
            userAddr.setDefaultAddr(CommonConstant.NO0);
        }
        userAddr.setUserId(userId);
        userAddr.setStatus(CommonConstant.STATUS_NORMAL_1);
        userAddr.setCreateTime(new Date());
        userAddr.setUpdateTime(new Date());
        userAddrService.insert(userAddr);
        
        if (userAddr.getDefaultAddr() == CommonConstant.YES1) {
            // 清除默认地址缓存
            userAddrService.removeUserAddrCache("0", userId);
        }
        return Result.ok("添加地址成功").data(userAddr.getId());
    }

    /**
     * 修改订单配送地址
     */
    @PutMapping("/updateAddr")
    @Log(oper = "修改订单用户地址")
    public Result updateAddr(@Valid @RequestBody AddrParam addrParam) {
        String userId = TokenUtils.getLoginUserid();

        UserAddr dbUserAddr = userAddrService.getUserAddrCache(addrParam.getId(), userId);
        if (dbUserAddr == null) {
            return Result.fail("该地址已被删除");
        }

        UserAddr userAddr = BeanUtil.copyProperties(addrParam, UserAddr.class);
        userAddr.setUserId(userId);
        userAddr.setUpdateTime(new Date());
        userAddrService.update(userAddr);
        // 清除当前地址缓存
        userAddrService.removeUserAddrCache(addrParam.getId(), userId);
        // 清除默认地址缓存
        userAddrService.removeUserAddrCache("0", userId);
        return Result.ok("修改地址成功");
    }

    /**
     * 删除订单配送地址
     */
    @Log(oper = "删除订单用户地址")
    @DeleteMapping("/deleteAddr/{addrId}")
    public Result deleteDvy(@PathVariable("addrId") String addrId) {
        String userId = TokenUtils.getLoginUserid();
        
        UserAddr userAddr = userAddrService.getUserAddrCache(addrId, userId);
        if (userAddr == null) {
            return Result.fail("该地址已被删除");
        }
        
        if (userAddr.getDefaultAddr() == CommonConstant.YES1) {
            return Result.fail("默认地址无法删除");
        }
        userAddrService.deleteById(addrId);
        userAddrService.removeUserAddrCache(addrId, userId);
        return Result.ok("删除地址成功");
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/defaultAddr/{addrId}")
    @Log(oper = "设置默认地址")
    public Result defaultAddr(@PathVariable("addrId") String addrId) {
        String userId = TokenUtils.getLoginUserid();

        userAddrService.updateDefaultAddr(addrId, userId);

        userAddrService.removeUserAddrCache("0", userId);
        userAddrService.removeUserAddrCache(addrId, userId);
        return Result.ok("修改地址成功");
    }

    /**
     * 获取地址信息订单配送地址
     */
    @GetMapping("/addrInfo/{addrId}")
    @Log(oper = "获取地址信息")
    public Result addrInfo(@PathVariable("addrId") String addrId) {
        String userId = TokenUtils.getLoginUserid();
        UserAddr userAddr = userAddrService.getUserAddrCache(addrId, userId);
        if (userAddr == null) {
        	return Result.fail("该地址已被删除");
        }
        return Result.ok(BeanUtil.copyProperties(userAddr, UserAddrVo.class));
    }

}
